package Homework;

import Homework.Student;

import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

public class CallName {
    public static void main(String[] args) {
        ArrayList<Student> students=new ArrayList<>();
        Scanner sc=new Scanner(System.in);
        addStudentName(students);
        printStudentName(students);
        System.out.println(randomStudentName(students));
    }
    public static  void printStudentName(ArrayList<Student> students){
        for(int i=0;i<students.size();i++){
        	Student s=students.get(i);
            System.out.println("第"+(i+1)+"个学生名称:"+s.getName()+"年龄"+s.getAge());
        }
    }
    public static void addStudentName(ArrayList<Student> students) {
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入要添加的学生数量：");
        int numStudents = sc.nextInt();
        
        sc.nextLine(); // 清除输入缓冲区的换行符

        for (int i = 0; i < numStudents; i++) {
            System.out.println("请输入第" + (i + 1) + "个学生的名称：");
            String name = sc.nextLine();
            System.out.println("请输入第" + (i + 1) + "个学生的年龄：");
            String test = sc.nextLine();
            if(!test.chars().allMatch(Character::isDigit)){
            	i=i-1;
            	System.out.println("年龄错误，请重新输入：");
            	continue;
            }//第一次判断是不是数字
            int age=Integer.parseInt(test);
			Student s = new Student();
            s.setName(name);
            
            try {
				s.setAge(age);
			} catch (AgeException e) {
				i=i-1;
            	System.out.println("年龄错误，请重新输入：");
            	continue;
			}//判断年龄是否合适
            students.add(s);
        }
    }
    public static String randomStudentName(ArrayList<Student> students){
        int index= new Random().nextInt(students.size());
        Student s=students.get(index);
        return "幸运儿:"+s.getName()+"  年龄:"+s.getAge();
    }
}
